#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int maxDistance(vector<vector<int>>& grid) {
        int n = grid.size();
        int dr[] = { -1,1,0,0 }, dc[] = { 0,0,-1,1 };
        vector<vector<bool>> vis(n, vector<bool>(n, false));
        queue<pair<int, int>> q;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    q.push({ i, j });
                    vis[i][j] = 1;
                }
            }
        }

        int ret = -1, distance = 0;
        while (!q.empty()) {
            int ct = q.size();
            while (ct--) {
                auto [r, c] = q.front();
                if (grid[r][c] == 0) {
                    ret = max(ret, distance);
                }
                q.pop();
                for (int i = 0; i < 4; i++) {
                    int nr = r + dr[i], nc = c + dc[i];
                    if (nr >= 0 && nr < n && nc >= 0 && nc < n && !vis[nr][nc]) {
                        q.push({ nr, nc });
                        vis[nr][nc] = 1;
                    }
                }
            }
            distance++;
        }
        return ret;
    }
};